import React, { lazy, Component, Suspense } from "react";
import { HashRouter, Routes, Route, Navigate } from "react-router-dom";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import Nprogress from "./loading";

const Home = lazy(() =>
  import(/* webpackChunkName:'home' */ "../pages/home/index")
);
const User = lazy(() =>
  import(/* webpackChunkName:'user' */ "../pages/user/index")
);
const Login = lazy(() =>
  import(/* webpackChunkName:'user' */ "../pages/login/index")
);
const View = lazy(() =>
  import(/* webpackChunkName:'view' */ "../pages/view/index")
);

export const baseRoutes = [
  {
    path: "/",
    element: Home,
    name: "Home",
    exact: true,
    meta: {
      title: "Home",
      auth: true,
    },
  },
  {
    path: "/user",
    element: User,
    name: "User",
    meta: {
      title: "User",
      auth: true,
    },
  },
  {
    path: "/login",
    element: Login,
    name: "Login",
    meta: {
      title: "Login",
      auth: false,
    },
  },
  {
    path: "/view",
    element: View,
    name: "View",
    meta: {
      title: "View",
      auth: false,
    },
  },
];

class RouteMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
    };
  }
  render() {
    let token = localStorage.getItem("Token");
    return (
      <TransitionGroup>
        <CSSTransition
          in={this.state.show}
          classNames="app_content"
          timeout={1000}
          unmountOnExit={true}
        >
          <Suspense fallback={<Nprogress />}>
            <HashRouter>
              <Routes>
                {baseRoutes.map((item, index) => {
                  return (
                    <Route
                      path={item.path}
                      element={
                        !item.meta.auth ? (
                          <item.element />
                        ) : token ? (
                          <item.element />
                        ) : (
                          <Navigate
                            to={{
                              pathname: "/login?source=" + window.location.href,
                              state: { from: this.props.location },
                            }}
                          />
                        )
                      }
                      exact={item.exact}
                      key={index}
                    />
                  );
                })}
              </Routes>
            </HashRouter>
          </Suspense>
        </CSSTransition>
      </TransitionGroup>
    );
  }
}

export default RouteMap;
